package com.chaopei.utils;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.util.Calendar;

/**
 * @Author Corday 天涯
 * @Date 2022/3/24 9:50
 */
public class MyTools {
    //oracle的用户名:scott
    static String username = "root";
    //oracle的密码最少6位:abcdef
    static String password = "1234";
    //oracle的驱动:oracle.jdbc.driver.OracleDriver
    static String driver = "com.mysql.jdbc.Driver";
    //oracle的url是:jdbc:oracle:thin:@127.0.0.1:1521:orcl
    static String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false&characterEncoding=utf8";

    //拿到数据库连接对象
    public static Connection getConn() {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    //2.关闭数据库连接对象
    public static void closeConn(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //    将日期对象转成当前的年龄
    public static int getAge(Date date) {
        //生成现在或当前的日历对象
        Calendar cd = Calendar.getInstance();
        //拿到当前的年份,月份
        int nowYear = cd.get(Calendar.YEAR);
        int nowMonth = cd.get(Calendar.MONTH);
        //拿到定义年份与月份,并转换为日历对象，此日历对象为重
        //新设置日期的对象
        cd.setTime(date);
        int beforeYear = cd.get(Calendar.YEAR);
        int beforeMonth = cd.get(Calendar.MONTH);
        //精确计算年龄
        int temp = 0;
        if (nowMonth > beforeMonth) {//当前的月份比出生的大
            temp = nowMonth - beforeMonth;
            temp = temp > 6 ? 1 : 0;
        } else {//出生的月份比当前的大或相等
            temp = beforeMonth - nowMonth;
            temp = temp > 6 ? -1 : 0;
        }
        int age = nowYear - beforeYear + temp;
        return age;
    }
}
